<?php

class IndexController extends ControllerBase
{
    public function initialize()
    {
        $this->tag->setTitle('欢迎');
        parent::initialize();
    }

    public function indexAction()
    {
        $auth = $this->session->get('auth');
        if(!$auth){
            $this->view->auth = false;
        }else{
            $testId = $this->session->get('auth')['testId'];
            $uid = $this->session->get('auth')['uid'];

            //输出视图变量
            $this->view->username = $this->session->get('auth')['name'];
            $this->view->auth = true;

            if($auth['role'] == 'normal'){
                //选择题目
                $test = Result::findFirst(array(
                    "user = :user: AND test = :test:",
                    'bind' => array('user' => $uid, 'test' => $testId)
                ));
                //如果没有被选中过
                if($test == false){
                    $this->_createTest($testId, $uid);
                }
                
            }else if($auth['role'] == 'admin'){
                $this->forward("admin/index");
            }
        }
        
    }

    public function reportsAction()
    {
        $this->view->username = $this->session->get('auth')['name'];
        $this->view->role = $this->session->get('auth')['role'];

        $testId = $this->session->get('auth')['testId'];
        $uid = $this->session->get('auth')['uid'];
        $this->view->finished = 1;
        $this->view->join = $this->_getJoinUserAction($testId);
        $this->view->finished = $this->_getFinishedUserAction($testId);
        $this->view->selfRatio = $this->_getSelfCorrectRatio($testId, $uid);
        $this->view->selfAchieve = $this->_getFinishedToAll($testId, $uid);
        $this->view->selfMark = $this->_getSelfMark($testId, $uid);
        $this->view->selfRank = $this->_getSelfRank($testId, $uid);
        $this->view->ratio = $this->_getTotalCorrectAction($testId);

        $result = $this->_getRankTen($testId);
        $this->view->ranks = $result['rank'];
        $this->view->names = $result['name'];
        $this->view->marks = $result['score'];
        $this->view->ratios = $result['ratio'];
        
        //$this->view->name = $result["name"];
        //$this->view->mark = $result["mark"];
    }

    public function helloAction()
    {
    	if(!$this->inject_check("insert")){
            echo "no!";
        }else{
            echo "yes!";
        }
    }

    private function _getRankTen($testId)
    {

        $results = Result::find(array(
            "test = :test:",
            'bind' => array('test' => $testId),
            'order' => 'mark DESC, ratio DESC'
        ));
        //按照mark和ratio降序排列

        $res = array();
        $rank = array();
        $name = array();
        $score = array();
        $ratio = array();
        $place = 1;
        $count = 0;
        $id = 0;

        $preResult = None;
        $flag = False;
        foreach ($results as $result) {
            
            if($preResult != None) {
                if($preResult->getMark() == $result->getMark()){
                    if($preResult->getRatio() == $result->getRatio()){
                        $place = $place;
                        $count = $count + 1;
                    }else{
                        $place = $place + 1 + $count;
                        $count = 0;
                        if($id > 10){
                            $flag = True;
                        }
                    }
                }else{
                    $place = $place + 1 + $count;
                    $count = 0;
                    if($id > 10){
                        $flag = True;
                    }
                }
            }
            if($flag)
                break;
            $name[$id] = $result->users->getName();
            $score[$id] = $result->getMark();
            $ratio[$id] = sprintf("%.2f", $result->getRatio() * 100)."%";
            $rank[$id] = $place;
            $id = $id + 1;

            $preResult = $result;
        }
        $res['name'] = $name;
        $res['score'] = $score;
        $res['ratio'] = $ratio;
        $res['rank'] = $rank;
        $res['size'] = $id;

        return $res;
    }

    private function _getJoinUserAction($testId)
    {
        $users = Result::find(array(
            "test = :test:",
            'bind' => array('test' => $testId)
        ));

        return count($users);
    }

    private function _getFinishedUserAction($testId)
    {
        $users = Result::find(array(
            "test = :test: AND checked = :checked:",
            'bind' => array('test' => $testId, 'checked' => 1)
        ));

        return count($users);
    }

    private function _getTotalCorrectAction($testId)
    {
        $ratio = Result::average(array(
            'column' => 'ratio',
            'conditions' => "checked = :checked: AND test = :test:",
            'bind' => array("checked" => 1, "test" => $testId) 
        ));

        return number_format($ratio * 100, 2)."%";
    }

    private function _getSelfCorrectRatio($testId,$uid)
    {
        $user = Result::findFirst(array(
            "test = :test: AND user = :uid:",
            'bind' => array('test' => $testId, 'uid' => $uid)
        ));

        return number_format($user->getRatio()*100, 2)."%";
    }

    private function _getSelfMark($testId,$uid){
        $user = Result::findFirst(array(
            "test = :test: AND user = :uid:",
            'bind' => array('test' => $testId, 'uid' => $uid)
        ));

        return "共得".number_format($user->getMark(), 0)."分";
    }

    private function _getSelfRank($testId,$uid){
        $results = Result::find(array(
            "test = :test:",
            'bind' => array('test' => $testId),
            'order' => 'mark DESC, ratio DESC'
        ));

        $count = 0;
        $rank = 0;
        $preResult = None;
        foreach ($results as $result) {
            
            if($preResult != None){
                if($preResult->getMark() == $result->getMark()){
                    if($preResult->getRatio() == $result->getRatio()){
                        $count = $count + 1;
                    }else{
                        $rank = $rank + 1 + $count;
                        $count = 0;
                    }
                }else{
                    $rank = $rank + 1 + $count;
                    $count = 0;
                }
            }

            $rank = $rank + 1;
            if($result->getUser() == $uid) {
                //如果查询到该用户退出
                break;
            }

        }
        return "第".number_format($rank, 0)."名";
    }

    //完成题目比例
    private function _getFinishedToAll($testId, $uid)
    {
        $finish = Answers::count(array(
            "checked = :checked: AND user = :user: AND test = :test:",
            'bind' => array('user' => $uid, 'test' => $testId, 'checked' => 1)
        ));
        $total = Answers::count(array(
            "user = :user: AND test = :test:",
            'bind' => array('user' => $uid, 'test' => $testId)
        ));

        return number_format($finish, 0)."/".number_format($total, 0);
    }

    //建立题目集
    private function _createTest($testId, $uid)
    {
        $result = new Result();
        $result->setUser($uid);
        $result->setTest($testId);
        $result->setMark(0);
        $result->setRatio(0);
        $result->setChecked(0);
        if($result->save() != false){
            $tests = TestDetails::find(array(
                "test = :test:",
                'bind' => array('test' => $testId),
                'order' => 'id' 
            ));
            
            if($tests != false){
                $id = 1;
                //生成随机题目顺序
                $sizeOfTests = count($tests);
                $group = rand(1, $sizeOfTests);   //[1,sizeOfTests]
                $beginGroup = rand(1, $group);  //[1,group]
                $groupSize = intval($sizeOfTests/$group);   //toInt

                //从开始组到倒数第二组
                for($i = $beginGroup-1; $i < $group-1; $i++){
                    for($j = 0; $j < $groupSize; $j++){
                        $answers = new Answers();
                        $answers->setUser($uid);
                        $answers->setNo($id);
                        $answers->setTest_db($tests[$i * $groupSize + $j]->getId());
                        $answers->setTest($testId);
                        $answers->setChoice(0);
                        $answers->setChecked(0);
                        $answers->save();
                        $id = $id + 1;
                    }
                }
                //处理最后一组
                for($t = $i * $groupSize; $t < $sizeOfTests; $t ++){
                    $answers = new Answers();
                    $answers->setUser($uid);
                    $answers->setNo($id);
                    $answers->setTest_db($tests[$t]->getId());
                    $answers->setTest($testId);
                    $answers->setChoice(0);
                    $answers->setChecked(0);
                    $answers->save();
                    $id = $id + 1;
                }
                //处理1到begingroup前一组
                for($i = 0; $i < $beginGroup-1; $i++){
                    for($j = 0; $j < $groupSize; $j++){
                        $answers = new Answers();
                        $answers->setUser($uid);
                        $answers->setNo($id);
                        $answers->setTest_db($tests[$i * $groupSize + $j]->getId());
                        $answers->setTest($testId);
                        $answers->setChoice(0);
                        $answers->setChecked(0);
                        $answers->save();
                        $id = $id + 1;
                    }
                }

                /*
                //顺序题目生成
                foreach($tests as $test){
                    
                    $answers = new Answers();
                    $answers->setUser($uid);
                    $answers->setNo($id);
                    $answers->setTest_db($test->getId());
                    $answers->setTest($testId);
                    $answers->setChoice(0);
                    $answers->setChecked(0);
                    $answers->save();
                    $id = $id + 1;
                }
                */
            }
        }
    }
}
